<?php
namespace Admin\Controller;
use Think\Controller;
class FormController extends Controller {
    private $_meta_title; // 页面标题
    private $_bread_crumb; //面包屑导航
    private $_tab_nav = array(); // 页面Tab导航
    private $_post_url; // 表单提交地址
    private $_form_items  = array(); // 表单项目
    private $_form_data   = array(); // 表单数据
    private $_template; // 模版
    private $_hiddenSubmit = false;  //提交按钮开关

    protected function _initialize()
    {
        $this->_template = 'builder/form/template';
    }
    //设置页面标题
    public function setMetaTitle($meta_title)
    {
        $this->_meta_title = $meta_title;
        return $this;
    }
    //设置面包屑导航
    public function setBreadCrumb($bread_crumb)
    {
        $this->_bread_crumb = $bread_crumb;
        return $this;
    }
    //设置tab导航
    public function setTabNav($tab_list)
    {
        $this->_tab_nav = $tab_list;
        return $this;
    }
    //设置表单提交地址
    public function setPostUrl($post_url)
    {
        $this->_post_url = $post_url;
        return $this;
    }
    //添加一个表单项
    public function addFormItem($name='', $type='', $title='', $tip='', $options = array(), $extra = '', $extra_attr = '')
    {
        $item['extra']   = array('class'=>'','required'=>false);
        $item['name']    = $name;
        $item['type']    = $type;
        $item['title']   = $title;
        $item['tip']     = $tip;
        $item['options'] = $options;
        if (is_array($extra)) {
            //$item['extra']['class'] = $extra['class'];
            $item['extra']['required']  = $extra['required'];
        } else {
            $item['extra']['class'] = $extra;
        }
        $item['extra']['attr'] = $extra_attr;
        $item['value']         = '';
        $this->_form_items[]   = $item;
        return $this;
    }
    //填充表单数据
    public function setFormData($form_data)
    {
        $this->_form_data = $form_data;
        return $this;
    }
    //隐藏提交按钮
    public function hiddenSubmit($hiddenSubmit){
        $this->_hiddenSubmit = $hiddenSubmit;
        return $this;
    }

    //显示页面
    public function fetch(){
      //填充表单值
      if ($this->_form_data) {
          foreach ($this->_form_items as &$item) {
              if (isset($item['name']) && isset($this->_form_data[$item['name']])) {
                  $item['value'] = $this->_form_data[$item['name']];
              }
          }
      }
      $this->assign('meta_title', $this->_meta_title);
      $this->assign('bread_crumb',$this->_bread_crumb);
      $this->assign('tab_nav', $this->_tab_nav);
      $this->assign('post_url', $this->_post_url);
      $this->assign('form_items', $this->_form_items);
      $this->assign('form_data', $this->_form_data);
      $this->assign('hiddenSubmit', $this->_hiddenSubmit);
      $this->display($this->_template);
    }
}
